<template>
  <div class="todo-footer" v-show="total">
    <label>
      <!-- <input type="checkbox" :checked="isAll" @click="checkAll" /> -->
      <!-- // 替代上面的方法 -->
      <input type="checkbox" v-model="isAll" />
      <span>
        <span>已完成{{ completed }} </span> / 全部 {{ total }}
      </span>
      <button class="btn btn-danger" @click="clearAll">清除已完成任务</button>
    </label>
  </div>
</template>

<script>
export default {
  name: "MyFooter",
  props: ["todos", "checkAllTodo", "clearAllTodo"],
  methods: {
    // checkAll(e) {
    //   console.log(e.target.checked);
    //   // if (e.target.checked) {
    //   //   this.todos.forEach((element) => {
    //   //     element.done = true;
    //   //   });
    //   // } else {
    //   //   this.todos.forEach((element) => {
    //   //     element.done = false;
    //   //   });
    //   // }
    //   checkAllTodo(e.target.checked);
    // },

    clearAll() {
      if (confirm("是否清除所有已完成？")) {
        this.clearAllTodo();
      }
    },
  },
  computed: {
    // computed 中默认方法调用的get读取方法，不能设置该值；如果需要修改该值，需要实现set方法
    isAll: {
      get() {
        return this.completed === this.total && this.total > 0;
      },
      set(value) {
        if (value) {
          this.todos.forEach((element) => {
            element.done = true;
          });
        } else {
          this.todos.forEach((element) => {
            element.done = false;
          });
        }
      },
      // return this.completed === this.total && this.total > 0;
    },
    total() {
      return this.todos.length;
    },
    completed() {
      // let sum = 0;
      // this.todos.forEach((element) => {
      //   if (element.done) {
      //     sum = sum + 1;
      //   }
      // });

      // let total = this.todos.reduce((previous, current) => {
      //   return previous + (current.done ? 1 : 0);
      // }, 0);

      return this.todos.reduce((prev, curr) => prev + (curr.done ? 1 : 0), 0);
    },
  },
};
</script>

<style scoped>
/** footer */
.todo-footer {
  height: 40px;
  line-height: 40px;
  padding-left: 6px;
  margin-top: 5px;
}
.todo-footer label {
  /* display: inline-block; */
  margin-right: 20px;
  cursor: pointer;
}
.todo-footer label input {
  position: relative;
  top: -1px;
  vertical-align: middle;
  margin-right: 5px;
}
.todo-footer button {
  float: right;
  margin-top: 5px;
}
</style>
